<?php
// Original doc comment
/*
* Open-Realty
*
* Open-Realty is free software; you can redistribute it and/or modify
* it under the terms of the Open-Realty License as published by
* Transparent Technologies; either version 1 of the License, or
* (at your option) any later version.
*
* Open-Realty is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* Open-Realty License for more details.
* http://www.open-realty.org/license_info.html
*
* You should have received a copy of the Open-Realty License
* along with Open-Realty; if not, write to Transparent Technologies
* RR1 Box 162C, Kingsley, PA  18826  USA
*
* @author Ryan C. Bonham <ryan@transparent-tech.com>
* @copyright Transparent Technologies 2004
* @link http://www.open-realty.org Open-Realty Project
* @link http://www.transparent-tech.com Transparent Technologies
* @link http://www.open-realty.org/license_info.html Open-Realty License
*/

/**
 * Google Maps Addon
 *
 * This addon adds the ability to utilize the Google Maps API with
 * Open-Realty.  It requires the latitude and longitude information for
 * each property's location to be stored in the database.  Most of the
 * features used can be adjusted using the administrator control panel.
 *
 * This addon has been tested using Open-Realty 2.2.0 and mysql 4.1.  It
 * should work with Open-Realty 2.1, but it will *not* work with prior
 * versions as it requires access to the global $jscript variable.  It
 * may be possible to use some of the functionality in previous versions
 * of OR by setting the "popup" field to Yes, but this has not been
 * tested.
 *
 * IMPORTANT!!
 * This addon does access your Open-Realty database, and adds tables and
 * inserts fields in existing tables when it installs. BACK UP YOUR DATA
 * FIRST!  I assume absolutely no responsibility for any data loss or any
 * other injury that may result from installing this addon, and specifically
 * disclaim ANY AND ALL WARRANTIES, including the implied warranties of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * The code in this addon borrows heavily from the Open-Realty source, so
 * some portions of this addon were authored by Ryan C. Bonham (and possibly
 * others), and as such are copyrighted by Transparent Technologies.
 *
 * All other code in this addon was authored by Jonathan Geist, and is
 * copyrighted as such.  Permission is hereby given to use and modify this
 * code in any manner, provided such code retains this copyright notice
 * and is released freely.
 *
 * Please send any bug reports to Jonathan Geist <jgeist@homereplay.com>
 * @author Jonathan Geist <jgeist@homereplay.com>
 * @copyright Jonathan Geist 2006. All rights reserved except where otherwise stated above.
 * @link http://www.homereplay.com/or/addons
 * @link http://www.open-realty.org Open-Realty Project
 * @link http://www.transparent-tech.com Transparent Technologies
 * @link http://www.open-realty.org/license_info.html Open-Realty License
 */


/**
 * install_addon()
 * This function should create and update any necessary database tables.
 * Developers can store version information for the addon in the addons table,
 * and use it to determine if an install or upgrade is needed.
 * @return
 **/
function googlemap_install_addon()
{
	$current_version = "1.0";
	global $conn, $config;
	require_once($config['basepath'].'/include/misc.inc.php');
	$misc = new misc();
	//Check Current Installed Version
	$sql = 'SELECT addons_version FROM '.$config['table_prefix_no_lang'].'addons WHERE addons_name = \'googlemap\'';
	$recordSet = $conn->Execute($sql);
	$version = $recordSet->fields[0];
	if ($version == '')
	{
		// Preform a new install. Create any needed databases etc, and insert version number into addon table.
		$sql = 'INSERT INTO '.$config['table_prefix_no_lang'].'addons (addons_version, addons_name) VALUES (\''.$current_version.'\',\'googlemap\')';
		$recordSet = $conn->Execute($sql);

		$sql = 'CREATE TABLE '.$config['table_prefix_no_lang'].'addon_googlemap (
			api_version 			SMALLINT,
			api_key					VARCHAR(255),
			popup					VARCHAR(3),
			search_dist 			DOUBLE,
			initial_zoom_level		SMALLINT,
			map_type				VARCHAR(20),
			map_height				VARCHAR(20),
			map_width				VARCHAR(20),
			info_bubble_template	VARCHAR(255),
			icon_image 				VARCHAR(255),
			icon_image_other		VARCHAR(255),
			icon_shadow 			VARCHAR(255),
			icon_iconSize_x			SMALLINT,
			icon_iconSize_y 		SMALLINT,
			icon_shadowSize_x 		SMALLINT,
			icon_shadowSize_y 		SMALLINT,
			icon_iconAnchor_x 		SMALLINT,
			icon_iconAnchor_y 		SMALLINT,
			icon_infoWindowAnchor_x SMALLINT,
			icon_infoWindowAnchor_y SMALLINT,
			map_control_type 		SMALLINT,
			map_control_anchor 		SMALLINT,
			map_control_padding_x 	SMALLINT,
			map_control_padding_y 	SMALLINT,
			type_control 			SMALLINT,
			type_control_anchor 	SMALLINT,
			type_padding_x 			SMALLINT,
			type_padding_y 			SMALLINT,
			scale_control 			SMALLINT,
			scale_control_anchor 	SMALLINT,
			scale_padding_x 		SMALLINT,
			scale_padding_y 		SMALLINT,
			overview_control 		SMALLINT,
			overview_control_anchor SMALLINT,
			overview_padding_x 		SMALLINT,
			overview_padding_y 		SMALLINT
			)';
		$recordSet = $conn->Execute($sql);
		if ($recordSet === false) {
			$misc->log_error($sql);
		}
		set_default_map_settings();

		// Make sure the database has fields for latitude and longitude
		//  and insert them if it doesn't.
		$sql = "SELECT * FROM " . $config['table_prefix'] . "listingsformelements WHERE listingsformelements_field_name = 'latitude' OR listingsformelements_field_name = 'longitude'";
		$recordSet = $conn->Execute($sql);
		if ($recordSet->RecordCount() == 0) {
			$sql = "SELECT class_id FROM " . $config['table_prefix'] . "class";
			$recordSet = $conn->Execute($sql);
			$count = 0;
			while (!$recordSet->EOF()) {
				$class_list[$count++] = $misc->make_db_unsafe ($recordSet->fields['class_id']);
				$recordSet->MoveNext();
			}

			insert_listing_field('text', 'latitude', 'Latitude', '', '', '0', '0', '0', 'No', '', 'No', '0', '2', '0', '', '', $class_list);
			insert_listing_field('text', 'longitude', 'Longitude', '', '', '0', '0', '0', 'No', '', 'No', '0', '2', '0', '', '', $class_list);
		}

		return TRUE;
	}
	elseif ($version != $current_version)
	{
	    //Preform Updates to database based on previous installed version.
		switch($version)
		{
	    	case '0';
				break;
	    } // switch
		return TRUE;
	}
	return FALSE;
}

/**
 * set_default_map_settings()
 * This function initializes (or resets) the initial map configuration settings.
 * @return nothing
 **/
function set_default_map_settings()
{
	global $conn, $config;
	// Get access to database functions
	require_once($config['basepath'].'/include/misc.inc.php');
	$misc = new misc();
	$sql = 'SELECT COUNT(*) FROM '.$config['table_prefix_no_lang'].'addon_googlemap';
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
	}
	// If the row with the googlemap addon's settings already exists,
	//  remove it before resetting to the default values.
	if ($recordSet->fields[0] > 0) {
		$sql = 'TRUNCATE '.$config['table_prefix_no_lang'].'addon_googlemap';
		$recordSet = $conn->Execute($sql);
		if ($recordSet === false) {
			$misc->log_error($sql);
		}
	}

	$sql = 'INSERT INTO '.$config['table_prefix_no_lang'].'addon_googlemap VALUES (';
	$sql .= '\'1\',';											// api_version
	$sql .= '\'\',';											// api_key
	$sql .= '\'No\',';											// popup
	$sql .= '\'5.0\',';											// search_dist
	$sql .= '\'2\',';											// initial_zoom_level
	$sql .= '\'NORMAL_MAP\',';									// map_type
	$sql .= '\'500px\',';										// map_height
	$sql .= '\'800px\',';										// map_width
	$sql .= '\'addons/googlemap/template/gm_popup.html\',';		// info_bubble_template
	$sql .= '\'addons/googlemap/images/gm_icon.gif\',';			// icon_image
	$sql .= '\'addons/googlemap/images/gm_icon_2.gif\',';		// icon_image_other
	$sql .= '\'addons/googlemap/images/gm_shadow.gif\',';		// icon_shadow
	$sql .= '\'32\',';											// icon_iconSize_x
	$sql .= '\'31\',';											// icon_iconSize_y
	$sql .= '\'52\',';											// icon_shadowSize_x
	$sql .= '\'26\',';											// icon_shadowSize_y
	$sql .= '\'16\',';											// icon_iconAnchor_x
	$sql .= '\'23\',';											// icon_iconAnchor_y
	$sql .= '\'16\',';											// icon_infoWindowAnchor_x
	$sql .= '\'4\',';											// icon_infoWindowAnchor_y
	$sql .= '\'3\',';											// map_control_type
	$sql .= '\'1\',';											// map_control_anchor
	$sql .= '\'0\',';											// map_control_padding_x
	$sql .= '\'0\',';											// map_control_padding_y
	$sql .= '\'2\',';											// type_control
	$sql .= '\'2\',';											// type_control_anchor
	$sql .= '\'0\',';											// type_padding_x
	$sql .= '\'0\',';											// type_padding_y
	$sql .= '\'1\',';											// scale_control
	$sql .= '\'3\',';											// scale_control_anchor
	$sql .= '\'0\',';											// scale_padding_x
	$sql .= '\'0\',';											// scale_padding_y
	$sql .= '\'1\',';											// overview_control
	$sql .= '\'4\',';											// overview_control_anchor
	$sql .= '\'1\',';											// overview_padding_x
	$sql .= '\'1\'';											// overview_padding_y
	$sql .= ')';
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
	}

}
/**
 * show_admin_icons()
 * This function should return an array of the html links that should be shown on the administrative page.
 * @return array should return each link that shoudl be shown in the admin section. Should return a string if it is a single link, or an array for multiple links.
 **/
function googlemap_show_admin_icons()
{
	global $config;
	$admin_link = '<a href="index.php?action=addon_googlemap_configure"><img src="'.$config['baseurl'].'/addons/googlemap/images/config.jpg" alt="Configure Google Maps"></img></a>';
	return $admin_link;
}
/**
 * load_template()
 * This should return an array with all the template tags for open-realty's template engine to parse
 * @return array List of template_fields
 **/
function googlemap_load_template()
{
	$template_array = array('addon_googlemap_link');
	return $template_array;
}
/**
 * run_action_user_template()
 * This function handles user $_GET[] actions related to the addon. Function must be named using this method: addon_addonname_description.
 * @return string Should return all contents that should be displayed when an addon specific $_GET['action'] is called.
 **/
function googlemap_run_action_user_template()
{
	switch ($_GET['action']) {
		case 'addon_googlemap_showmap':
			$data = googlemap_display_addon_page();
			break;
		default:
			$data = '';
			break;
	} // End switch ($_GET['action'])
	return $data;
}
/**
 * run_action_admin_template()
 * This function handles administrative $_GET[] actions related to the addon. Function must be named using this method: addon_addonname_description.
 * @return string Should return all contents that should be displayed when a addon specific $_GET['action'] is called.
 **/
function googlemap_run_action_admin_template()
{
	switch ($_GET['action']) {
		case 'addon_googlemap_configure':
			$data = googlemap_display_admin_page();
			break;
		default:
			$data = '';
			break;
	} // End switch ($_GET['action'])
	return $data;
}
/**
 * run_template_user_fields()
 * This function handles all the replacement of {template_tags} with the actual content. All tags setup here must also be added to teh load_template function in order for open-realty to parse them.
 * @param string $tag
 * @return string Should return all contents that should be displayed when a addon specific $tag is called.
 **/
function googlemap_run_template_user_fields($tag = '')
{
	global $conn, $config;
	switch ($tag) {
		case 'addon_googlemap_link':
			$data = googlemap_display_addon_link();
			break;
        case 'addon_googlemap_display':
			$data = googlemap_display_addon_page();
			break;
         case 'addon_googlemap_home':
			$data = googlemap_display_addon_home();
			break;

		default:
			$data = '';
			break;
	} // End switch ($_GET['action'])
	return $data;
}

/**
 * googlemap_display_addon_link()
 * This function generates the link to the Google Map.  If either of the latitude or
 * longitude fields for the current listing are not set, it returns a link to the old
 * (default Open-Realty) map.
 *
 * @return string Returns a hyperlink that will load the map when clicked.
 */
function googlemap_display_addon_link()
{
	// Need access to common path information, and current connection
	global $config,$lang,$conn;

	// Get access to database functions
	require_once($config['basepath'].'/include/misc.inc.php');
	$misc = new misc();

	$listingID = $misc->make_db_safe($_GET['listingID']);

	// grab latitude and longitude of current listing
	$sql = "SELECT listingsdbelements_field_value FROM " . $config['table_prefix'] . "listingsdbelements WHERE (listingsdb_id = $listingID AND (listingsdbelements_field_name = 'latitude' OR listingsdbelements_field_name = 'longitude'))";
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
		}
	$val1 = $misc->make_db_unsafe ($recordSet->fields['listingsdbelements_field_value']);
	$recordSet->MoveNext();
	$val2 = $misc->make_db_unsafe ($recordSet->fields['listingsdbelements_field_value']);

	// if (latitude and longitude) are set for the current listing
	if (!($val1 == '') && !($val2 == '')) {
		$sql = "SELECT * FROM " . $config['table_prefix_no_lang'] . "addon_googlemap";
		$recordSet = $conn->Execute($sql);
		if ($recordSet === false) {
			$misc->log_error($sql);
			}
		$popup = $misc->make_db_unsafe ($recordSet->fields['popup']);
		// Open map in a pop up window?
		if ($popup == 1){
			$map_height=$misc->make_db_unsafe ($recordSet->fields['map_height']);
			$map_width=$misc->make_db_unsafe ($recordSet->fields['map_width']);
			$display = '<a href="index.php?action=addon_googlemap_showmap&listingID='.$_GET['listingID']."&popup=1\" onclick=\"window.open(this.href,'_map','location=0,status=0,scrollbars=1,toolbar=0,menubar=0,width=$map_width,height=$map_height');return false\">";
			$display .= '<img src="template/dd2col/images/viewmap.jpg" alt="click to view google map"/></a>';
		}
		else {
			$display = '<a href="index.php?action=addon_googlemap_showmap&listingID='.$_GET['listingID'].'">'.$lang[map_link].'</a>';
		}
		return $display;
	}
	// Fail gracefully if latitude or longitude not set.
	require_once($config['basepath'] . '/include/maps.inc.php');
	$map = new maps();
	return $map->create_map_link();
}

/**
 * googlemap_display_addon_page()
 * This function generates the google map html and javascript for adding to
 * the template in the {content} tag.
 * @return Returns the Google Map
 */
function googlemap_display_addon_page()
{
	$display = init_map();
	return $display;
}

function googlemap_display_addon_home()
{
	$display = init_map2();
	return $display;
}


/**
 * googlemap_display_admin_page()
 * This is called when configuring the googlemap addon via the admin page.
 * @return The html form for configuring the googlemap addon
 */
function googlemap_display_admin_page()
{
	$display = generate_admin_config_page();
	return $display;
}

/**
 * This function generates the code to display a map in the content section of the listing
 * page using the Google Maps API.  It will add data points with pop-up html information
 * bubbles for the current listing, and any other listings within a set distance.
 *
 * This function stores the javascript to generate the map in the global $jscript variable.
 * @return The javascript to display the map in the body of the document.
 */
function init_map()
{
	// Need access to common path information, javascript variable, and current connection
	global $config,$lang,$conn,$jscript;

	// Get access to database functions
	require_once($config['basepath'].'/include/misc.inc.php');
	$misc = new misc();

	$listingID = $_GET['listingID'];

	// Set standard map control arrays
	$map_type_[1] = 'NORMAL_MAP';
	$map_type_[2] = 'SATELLITE_MAP';
	$map_type_[3] = 'HYBRID_MAP';

	$map_control_[1] = 'none';
	$map_control_[2] = 'LargeMapControl';
	$map_control_[3] = 'SmallMapControl';
	$map_control_[4] = 'SmallZoomControl';

	$map_anchor[1] = 'TOP_LEFT';
	$map_anchor[2] = 'TOP_RIGHT';
	$map_anchor[3] = 'BOTTOM_LEFT';
	$map_anchor[4] = 'BOTTOM_RIGHT';

	$type_control_[1] = 'none';
	$type_control_[2] = 'MapTypeControl';

	$scale_control_[1] = 'none';
	$scale_control_[2] = 'ScaleControl';

	$overview_control_[1] = 'none';
	$overview_control_[2] = 'OverviewMapControl';

	// Set addon vars from database
	$sql = 'SELECT * FROM ' . $config['table_prefix_no_lang'] . 'addon_googlemap';
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
		}
	$api_version=$misc->make_db_unsafe ($recordSet->fields['api_version']);
    $api_key=$misc->make_db_unsafe ($recordSet->fields['api_key']);
	$popup=$misc->make_db_unsafe ($recordSet->fields['popup']);
	$search_dist=$misc->make_db_unsafe ($recordSet->fields['search_dist']);
	$initial_zoom_level=$misc->make_db_unsafe ($recordSet->fields['initial_zoom_level']);
	$map_type=$misc->make_db_unsafe ($recordSet->fields['map_type']);
	$map_height=$misc->make_db_unsafe ($recordSet->fields['map_height']);
	$map_width=$misc->make_db_unsafe ($recordSet->fields['map_width']);
	$info_bubble_template=$misc->make_db_unsafe ($recordSet->fields['info_bubble_template']);
	$icon_image=$misc->make_db_unsafe ($recordSet->fields['icon_image']);
	$icon_image_other=$misc->make_db_unsafe ($recordSet->fields['icon_image_other']);
	$icon_shadow=$misc->make_db_unsafe ($recordSet->fields['icon_shadow']);
	$icon_iconSize_x=$misc->make_db_unsafe ($recordSet->fields['icon_iconSize_x']);
	$icon_iconSize_y=$misc->make_db_unsafe ($recordSet->fields['icon_iconSize_y']);
	$icon_shadowSize_x=$misc->make_db_unsafe ($recordSet->fields['icon_shadowSize_x']);
	$icon_shadowSize_y=$misc->make_db_unsafe ($recordSet->fields['icon_shadowSize_y']);
	$icon_iconAnchor_x=$misc->make_db_unsafe ($recordSet->fields['icon_iconAnchor_x']);
	$icon_iconAnchor_y=$misc->make_db_unsafe ($recordSet->fields['icon_iconAnchor_y']);
	$icon_infoWindowAnchor_x=$misc->make_db_unsafe ($recordSet->fields['icon_infoWindowAnchor_x']);
	$icon_infoWindowAnchor_y=$misc->make_db_unsafe ($recordSet->fields['icon_infoWindowAnchor_y']);
	$map_control_type=$misc->make_db_unsafe ($recordSet->fields['map_control_type']);
	$map_control_anchor=$misc->make_db_unsafe ($recordSet->fields['map_control_anchor']);
	$map_control_padding_x=$misc->make_db_unsafe ($recordSet->fields['map_control_padding_x']);
	$map_control_padding_y=$misc->make_db_unsafe ($recordSet->fields['map_control_padding_y']);
	$type_control=$misc->make_db_unsafe ($recordSet->fields['type_control']);
	$type_control_anchor=$misc->make_db_unsafe ($recordSet->fields['type_control_anchor']);
	$type_padding_x=$misc->make_db_unsafe ($recordSet->fields['type_padding_x']);
	$type_padding_y=$misc->make_db_unsafe ($recordSet->fields['type_padding_y']);
	$scale_control=$misc->make_db_unsafe ($recordSet->fields['scale_control']);
	$scale_control_anchor=$misc->make_db_unsafe ($recordSet->fields['scale_control_anchor']);
	$scale_padding_x=$misc->make_db_unsafe ($recordSet->fields['scale_padding_x']);
	$scale_padding_y=$misc->make_db_unsafe ($recordSet->fields['scale_padding_y']);
	$overview_control=$misc->make_db_unsafe ($recordSet->fields['overview_control']);
	$overview_control_anchor=$misc->make_db_unsafe ($recordSet->fields['overview_control_anchor']);
	$overview_padding_x=$misc->make_db_unsafe ($recordSet->fields['overview_padding_x']);
	$overview_padding_y=$misc->make_db_unsafe ($recordSet->fields['overview_padding_y']);

	// grab latitude of current listing
	$sql = "SELECT listingsdbelements_field_value FROM " . $config['table_prefix'] . "listingsdbelements WHERE (listingsdb_id = $listingID AND listingsdbelements_field_name = 'latitude')";
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($ssql);
		}
	$latitude = $misc->make_db_unsafe ($recordSet->fields['listingsdbelements_field_value']);

	// grab longitude of current listing
	$sql = "SELECT listingsdbelements_field_value FROM " . $config['table_prefix'] . "listingsdbelements WHERE (listingsdb_id = $listingID AND listingsdbelements_field_name = 'longitude')";
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
		}
	$longitude = $misc->make_db_unsafe ($recordSet->fields['listingsdbelements_field_value']);

	$lat_dist = $search_dist / 69.0;
	$long_dist = $search_dist / abs(cos($latitude) * 69.17);

	// select all active listings whose latitude is within the search distance of the current listing's latitude
	$listingsdb = $config['table_prefix'] . "listingsdb";
	$listingsdbelements = $config['table_prefix'] . "listingsdbelements";

	$sql = "SELECT " . $listingsdbelements . ".* FROM $listingsdbelements, $listingsdb WHERE " . $listingsdb . ".listingsdb_id = " . $listingsdbelements . ".listingsdb_id AND " . $listingsdb . ".listingsdb_active = 'yes' AND (" . $listingsdbelements . ".listingsdbelements_field_name = 'latitude' AND ABS(" . $listingsdbelements . ".listingsdbelements_field_value - $latitude) < $lat_dist)";
	// don't select expired listings if we're filtering expired listings.
	if ($config['use_expiration'] == 1) {
		$sql .= " AND (" . $listingsdb . ".listingsdb_expiration > " . $conn->DBDate(time()) . ")";
	}
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
		}

	// If there are any properties within dist of listing latitude
	if ($recordSet <> false) {
		$count=0;

		// Loop through the entire set of properties found
		while (!$recordSet->EOF()){
			$pid=$misc->make_db_unsafe ($recordSet->fields['listingsdb_id']);

			// If the current property is the current listing, handle it separately
			// in order to center map on it.
			if ($pid==$listingID)
			{
				// Get the listing's thumbnail image.
				$irec=$conn->Execute("SELECT listingsimages_thumb_file_name FROM " . $config['table_prefix'] . "listingsimages WHERE listingsdb_id = $pid AND listingsimages_rank = 1");
				$fn=$misc->make_db_unsafe ($irec->fields['listingsimages_thumb_file_name']);
				$ilink=$config['baseurl']."/images/listing_photos/".$fn;

				// Gather the listing elements fields that will be used to generate
				// the html for the pop-up bubble
				$pinfo=$conn->Execute("SELECT listingsdbelements_field_name, listingsdbelements_field_value FROM " . $config['table_prefix'] . "listingsdbelements WHERE listingsdbelements_field_name IN ('address','city','state','zip','price') AND listingsdb_id = $pid");

				// Take the field information from the result set.
				// This is kind of kludgy - need to try to find either a better way
				//  of doing this, or use individual db calls to get fields.
				// Need to determine whether db calls are faster than php.
				while (!$pinfo->EOF()){
					switch ($pinfo->fields['listingsdbelements_field_name']) {
						case 'address':
							$address=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
						break;
						case 'city':
							$city=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
						break;
						case 'state':
							$state=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
						break;
						case 'zip':
							$zip=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
						break;
						case 'price':
							$price=$misc->money_formats ($misc->international_num_format($misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']), $config['number_decimals_price_fields']));
						break;
					} // switch

					$pinfo->MoveNext();
				} // while

				// Grab the listing title for the pop-up bubble
				$pinfo2=$conn->Execute("SELECT listingsdb_title FROM " . $config['table_prefix'] . "listingsdb WHERE listingsdb_id = $pid");
				$title=$misc->make_db_unsafe ($pinfo2->fields['listingsdb_title']);

				// Generate the html for the Google Map pop-up information bubble for this property.
				// *** Change this to code that pulls the html from a template file. ***

				$link = '<a href="'.$config['baseurl'].'/index.php?action=listingview&listingID='.$pid.'">';
				$gmhtml="'".'<table><tr><td align="center"><b>'. $link . $title . ' </a></b></td></tr><tr><td>';
				$gmhtml.= $link . '<img src="'.$ilink.'" altd="no image"></img></a>';
				$gmhtml.= '</td><td><b>Listing Price: '.$price.'<br><br>Property Address:</b><br>'.$address.'<br>'.$city. ', ' .$state.' '.$zip .'</td></tr></table>'."'";

				// Save the coordinates and html for the center point on the map
				$centerpoint['latitude']=$latitude;
				$centerpoint['longitude']=$longitude;
				$centerpoint['html']=$gmhtml;
			} // end if current listing

			// This is not the current listing
			else
			{
				// Get the coordinates of this data point
				$py=$misc->make_db_unsafe ($recordSet->fields['listingsdbelements_field_value']);
				$prec=$conn->Execute("SELECT * FROM " . $config['table_prefix'] . "listingsdbelements WHERE listingsdbelements_field_name = 'longitude' AND listingsdb_id = $pid");
				$px=$misc->make_db_unsafe ($prec->fields['listingsdbelements_field_value']);
				// Add this property if its longitude is less than the search distance from
				//  the current listing's.
				if (abs($px - $longitude) < $long_dist)
				{
					// Get the listing's thumbnail image.
					$irec=$conn->Execute("SELECT listingsimages_thumb_file_name FROM " . $config['table_prefix'] . "listingsimages WHERE listingsdb_id = $pid AND listingsimages_rank = 1");
					$fn=$misc->make_db_unsafe ($irec->fields['listingsimages_thumb_file_name']);
					$ilink=$config['baseurl']."/images/listing_photos/".$fn;

					// Gather the listing elements fields that will be used to generate
					// the html for the pop-up bubble
					$pinfo=$conn->Execute("SELECT listingsdbelements_field_name, listingsdbelements_field_value FROM " . $config['table_prefix'] . "listingsdbelements WHERE listingsdbelements_field_name IN ('address','city','state','zip','price') AND listingsdb_id = $pid");

					// Take the field information from the result set.
					// This is kind of kludgy - need to try to find either a better way
					//  of doing this, or use individual db calls to get fields.
					// Need to determine whether db calls are faster than php.
					while (!$pinfo->EOF()){
						switch ($pinfo->fields['listingsdbelements_field_name']) {
							case 'address':
								$address=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
							break;
							case 'city':
								$city=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
							break;
							case 'state':
								$state=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
							break;
							case 'zip':
								$zip=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
							break;
							case 'price':
								$price=$misc->money_formats ($misc->international_num_format($misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']), $config['number_decimals_price_fields']));
							break;
						} //switch

						$pinfo->MoveNext();
					} // while

					// Grab the listing title for the pop-up bubble
					$pinfo2=$conn->Execute("SELECT listingsdb_title FROM " . $config['table_prefix'] . "listingsdb WHERE listingsdb_id = $pid");
					$title=$misc->make_db_unsafe ($pinfo2->fields['listingsdb_title']);

					// Generate the html for the Google Map pop-up information bubble for this property.
					// *** Change this to code that pulls the html from a template file. ***
					$link = '<a href="'.$config['baseurl'].'/index.php?action=listingview&listingID='.$pid.'">';
					$gmhtml="'".'<table cellpadding="5"><tr><td align="center"><b>'. $link . $title . ' </a></b></td></tr>';
					$gmhtml.= '<tr><td><div class="thumbnail">'.$link.'<img src="'.$ilink.'" alt="no image"></img></a></div></td>';
					$gmhtml.= '<td><b>Listing Price: '.$price.'<br><br>Property Address:</b><br>'.$address.'<br>'.$city. ', ' .$state.' '.$zip .'</td></tr></table>'."'";

					// Save the coordinates and html for this data point in an array
					$otherpoint[$count]['latitude']=$py;
					$otherpoint[$count]['longitude']=$px;
					$otherpoint[$count++]['html']=$gmhtml;
				} // if
			} // else
		$recordSet->MoveNext();
		} // while
	} // end If there are any properties within dist of listing latitude

	// Generate the javascript for the map page.
	// This all goes in the header block
	$gscript.= '<style type="text/css">'."\n";
    $gscript.= '	v\:* {'."\n";
    $gscript.= '		behavior:url(#default#VML);'."\n";
    $gscript.= '	}'."\n";
    $gscript.= '</style>'."\n";

	// Set the script source and api key
	//  Note that we use v=2 even if the api_version is set to 1.  The
	//	Google API documentation states that backward compatibility should
	//	be maintained in v2, but using v=1 may break at any time.  Setting
	//	api_version to 1 will use the old GMap class and associated methods.
	$gscript.= '<script src="http://maps.google.com/maps?file=api&v=2&key=' . $api_key . '" type="text/javascript"></script>'."\n";
	$gscript.= '<script type="text/javascript">'."\n";

	// Set the basic map properties
	$gscript.= '//<![CDATA['."\n"."\n";

    $gscript.= 'function onLoad() {'."\n";
    $gscript.= '	// The Basics'."\n";
    $gscript.= '	//'."\n";
    $gscript.= '	// Taken more or less from the google API examples and modified to fit'."\n";
    $gscript.= '	var icon = new GIcon();'."\n";
    $gscript.= '	icon.image = "'. $config["baseurl"] . '/' . $icon_image_other .'";'."\n";
    $gscript.= '	icon.shadow = "'. $config["baseurl"] . '/' . $icon_shadow .'";'."\n";
    $gscript.= '	icon.iconSize = new GSize('.$icon_iconSize_x.', '.$icon_iconSize_y.');'."\n";
    $gscript.= '	icon.shadowSize = new GSize('.$icon_shadowSize_x.', '.$icon_shadowSize_y.');'."\n";
    $gscript.= '	icon.iconAnchor = new GPoint('.$icon_iconAnchor_x.', '.$icon_iconAnchor_y.');'."\n";
    $gscript.= '	icon.infoWindowAnchor = new GPoint('.$icon_infoWindowAnchor_x.', '.$icon_infoWindowAnchor_y.');'."\n";
    $gscript.= '	var cicon = new GIcon();'."\n";
    $gscript.= '	cicon.image = "'. $config["baseurl"] . '/' . $icon_image .'";'."\n";
    $gscript.= '	cicon.shadow = "'. $config["baseurl"] . '/' . $icon_shadow .'";'."\n";
    $gscript.= '	cicon.iconSize = new GSize('.$icon_iconSize_x.', '.$icon_iconSize_y.');'."\n";
    $gscript.= '	cicon.shadowSize = new GSize('.$icon_shadowSize_x.', '.$icon_shadowSize_y.');'."\n";
    $gscript.= '	cicon.iconAnchor = new GPoint('.$icon_iconAnchor_x.', '.$icon_iconAnchor_y.');'."\n";
    $gscript.= '	cicon.infoWindowAnchor = new GPoint('.$icon_infoWindowAnchor_x.', '.$icon_infoWindowAnchor_y.');'."\n";
	if ($api_version == 1) {
	    $gscript.= '	var map = new GMap(document.getElementById("map"));'."\n";
		$gscript.= '	map.setMapType(G_'.$map_type_[$map_type].');'."\n";
    	$gscript.= '	map.centerAndZoom(new GPoint('.$centerpoint['longitude'].','.$centerpoint['latitude'].'),'.$initial_zoom_level.');'."\n";
	}
	else {
	    $gscript.= '	var map = new GMap2(document.getElementById("map"));'."\n";
    	$gscript.= '	map.setCenter(new GLatLng('.$centerpoint['latitude'].','.$centerpoint['longitude'].'),'.$initial_zoom_level.', G_'.$map_type_[$map_type].');'."\n";
	}
	if ($map_control_[$map_control_type] !='none') {
		if ($api_version == 1) {
		    $gscript.= '	map.addControl(new G'. $map_control_[$map_control_type] .'());'."\n";
		}
		else {
		    $gscript.= '	map.addControl(new G'. $map_control_[$map_control_type] .'(), new GControlPosition(G_ANCHOR_'.$map_anchor[$map_control_anchor].', new GSize('.$map_control_padding_x.', '.$map_control_padding_y.')));'."\n";
		}
	}
	if ($type_control_[$type_control] !='none') {
		if ($api_version == 1) {
		    $gscript.= '	map.addControl(new G'. $type_control_[$type_control] .'());'."\n";
		}
		else {
		    $gscript.= '	map.addControl(new G'. $type_control_[$type_control] .'(), new GControlPosition(G_ANCHOR_'.$map_anchor[$type_control_anchor].', new GSize('.$type_padding_x.', '.$type_padding_y.')));'."\n";
		}
	}
	if ($scale_control_[$scale_control] !='none') {
		if ($api_version == 1) {
		    $gscript.= '	map.addControl(new G'. $scale_control_[$scale_control] .'());'."\n";
		}
		else {
		    $gscript.= '	map.addControl(new G'. $scale_control_[$scale_control] .'(), new GControlPosition(G_ANCHOR_'.$map_anchor[$scale_control_anchor].', new GSize('.$scale_padding_x.', '.$scale_padding_y.')));'."\n";
		}
	}
	if ($overview_control_[$overview_control] !='none') {
		if ($api_version == 1) {
		}
		else {
		    $gscript.= '	map.addControl(new G'. $overview_control_[$overview_control] .'(), new GControlPosition(G_ANCHOR_'.$map_anchor[$overview_control_anchor].', new GSize('.$overview_padding_x.', '.$overview_padding_y.')));'."\n";
		}
	}

	$gscript.="\n";
    $gscript.= '	// Add the current listing to the map and center the map on that location.'."\n";
	if ($api_version == 1) {
	    $gscript.= '	var cpoint = new GPoint('.$centerpoint['longitude'].','.$centerpoint['latitude'].');'."\n";
	}
	else {
	    $gscript.= '	var cpoint = new GLatLng('.$centerpoint['latitude'].','.$centerpoint['longitude'].');'."\n";
	}
    $gscript.= '	var cmarker = new GMarker(cpoint, cicon);'."\n";
    $gscript.= '	GEvent.addListener(cmarker,'."'click'".', function() {'."\n";
    $gscript.= '		cmarker.openInfoWindowHtml('.$centerpoint['html'].');'."\n";
    $gscript.= '		});'."\n";
    $gscript.= '	map.addOverlay(cmarker);'."\n"."\n";
    $gscript.= ' 	// Add other properties to the map'."\n";
	// Loop through the array and add all the other properties found within
	//  our set distance.
    for ($i=0; $i<$count; $i++)
    {
		$gscript.="\n";
		if ($api_version == 1) {
	    $gscript.='	var point'.$i.' = new GPoint('.$otherpoint[$i]['longitude'].','.$otherpoint[$i]['latitude'].');'."\n";
		}
		else {
        $gscript.='	var point'.$i.' = new GLatLng('.$otherpoint[$i]['latitude'].','.$otherpoint[$i]['longitude'].');'."\n";
		}
        $gscript.='	var marker'.$i.' = new GMarker(point'.$i.', icon);'."\n";
        $gscript.='	GEvent.addListener(marker'.$i.','."'click'".', function() {'."\n";
        $gscript.='	     	marker'.$i.'.openInfoWindowHtml('.$otherpoint[$i]['html'].');'."\n";
        $gscript.='	        });'."\n";
        $gscript.='	map.addOverlay(marker'.$i.');'."\n";
     }

	  // End the map javascript
      $gscript .= '	}'."\n".'//]]>'."\n".'</script>'."\n";

	if ($popup == 1) {
		$display = "<html>\n<head>\n";
		$display .= $gscript;
		$display .= "</head>";
		if ($api_version == 1) {
			$display .='<body onload="onLoad()">';
		}
		else {
			$display .='<body onload="onLoad()" onunload="GUnload()">';
		}
		$display .='<div id="map" style="width: '.$map_width.'; height: '.$map_height.'"></div></body>';
		$display .="</body>";
	}
	else {
		// This is the code that allows the map to be shown in the main browser window, instead
		//  of in a pop-up.
		$jscript=$gscript;
		$display = '';
		if ($api_version == 1) {
			$display .='<body onload="onLoad()">';
		}
		else {
			$display .='<body onload="onLoad()" onunload="GUnload()">';
		}
		$display .='<div id="map" style="width: '.$map_width.'; height: '.$map_height.'"></div></body>';
	}
	return $display;
}  // end init_map()

function init_map2()
{
	// Need access to common path information, javascript variable, and current connection
	global $config,$lang,$conn,$jscript;

	// Get access to database functions
	require_once($config['basepath'].'/include/misc.inc.php');
	$misc = new misc();

	$listingID = 6;

	// Set standard map control arrays
	$map_type_[1] = 'NORMAL_MAP';
	$map_type_[2] = 'SATELLITE_MAP';
	$map_type_[3] = 'HYBRID_MAP';

	$map_control_[1] = 'none';
	$map_control_[2] = 'LargeMapControl';
	$map_control_[3] = 'SmallMapControl';
	$map_control_[4] = 'SmallZoomControl';

	$map_anchor[1] = 'TOP_LEFT';
	$map_anchor[2] = 'TOP_RIGHT';
	$map_anchor[3] = 'BOTTOM_LEFT';
	$map_anchor[4] = 'BOTTOM_RIGHT';

	$type_control_[1] = 'none';
	$type_control_[2] = 'MapTypeControl';

	$scale_control_[1] = 'none';
	$scale_control_[2] = 'ScaleControl';

	$overview_control_[1] = 'none';
	$overview_control_[2] = 'OverviewMapControl';

	// Set addon vars from database
	$sql = 'SELECT * FROM ' . $config['table_prefix_no_lang'] . 'addon_googlemap';
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
		}
	$api_version=$misc->make_db_unsafe ($recordSet->fields['api_version']);
    $api_key=$misc->make_db_unsafe ($recordSet->fields['api_key']);
	$popup=$misc->make_db_unsafe ($recordSet->fields['popup']);
	$search_dist=$misc->make_db_unsafe ($recordSet->fields['search_dist']);
	$initial_zoom_level='13';
	$map_type=$misc->make_db_unsafe ($recordSet->fields['map_type']);
	$map_height=$misc->make_db_unsafe ($recordSet->fields['map_height']);
	$map_width=$misc->make_db_unsafe ($recordSet->fields['map_width']);
	$info_bubble_template=$misc->make_db_unsafe ($recordSet->fields['info_bubble_template']);
	$icon_image=$misc->make_db_unsafe ($recordSet->fields['icon_image']);
	$icon_image_other=$misc->make_db_unsafe ($recordSet->fields['icon_image_other']);
	$icon_shadow=$misc->make_db_unsafe ($recordSet->fields['icon_shadow']);
	$icon_iconSize_x=$misc->make_db_unsafe ($recordSet->fields['icon_iconSize_x']);
	$icon_iconSize_y=$misc->make_db_unsafe ($recordSet->fields['icon_iconSize_y']);
	$icon_shadowSize_x=$misc->make_db_unsafe ($recordSet->fields['icon_shadowSize_x']);
	$icon_shadowSize_y=$misc->make_db_unsafe ($recordSet->fields['icon_shadowSize_y']);
	$icon_iconAnchor_x=$misc->make_db_unsafe ($recordSet->fields['icon_iconAnchor_x']);
	$icon_iconAnchor_y=$misc->make_db_unsafe ($recordSet->fields['icon_iconAnchor_y']);
	$icon_infoWindowAnchor_x=$misc->make_db_unsafe ($recordSet->fields['icon_infoWindowAnchor_x']);
	$icon_infoWindowAnchor_y=$misc->make_db_unsafe ($recordSet->fields['icon_infoWindowAnchor_y']);
	$map_control_type=$misc->make_db_unsafe ($recordSet->fields['map_control_type']);
	$map_control_anchor=$misc->make_db_unsafe ($recordSet->fields['map_control_anchor']);
	$map_control_padding_x=$misc->make_db_unsafe ($recordSet->fields['map_control_padding_x']);
	$map_control_padding_y=$misc->make_db_unsafe ($recordSet->fields['map_control_padding_y']);
	$type_control=$misc->make_db_unsafe ($recordSet->fields['type_control']);
	$type_control_anchor=$misc->make_db_unsafe ($recordSet->fields['type_control_anchor']);
	$type_padding_x=$misc->make_db_unsafe ($recordSet->fields['type_padding_x']);
	$type_padding_y=$misc->make_db_unsafe ($recordSet->fields['type_padding_y']);
	$scale_control=$misc->make_db_unsafe ($recordSet->fields['scale_control']);
	$scale_control_anchor=$misc->make_db_unsafe ($recordSet->fields['scale_control_anchor']);
	$scale_padding_x=$misc->make_db_unsafe ($recordSet->fields['scale_padding_x']);
	$scale_padding_y=$misc->make_db_unsafe ($recordSet->fields['scale_padding_y']);
	$overview_control=$misc->make_db_unsafe ($recordSet->fields['overview_control']);
	$overview_control_anchor=$misc->make_db_unsafe ($recordSet->fields['overview_control_anchor']);
	$overview_padding_x=$misc->make_db_unsafe ($recordSet->fields['overview_padding_x']);
	$overview_padding_y=$misc->make_db_unsafe ($recordSet->fields['overview_padding_y']);

	// grab latitude of current listing
	$sql = "SELECT listingsdbelements_field_value FROM " . $config['table_prefix'] . "listingsdbelements WHERE (listingsdb_id = $listingID AND listingsdbelements_field_name = 'latitude')";
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($ssql);
		}
	$latitude = $misc->make_db_unsafe ($recordSet->fields['listingsdbelements_field_value']);

	// grab longitude of current listing
	$sql = "SELECT listingsdbelements_field_value FROM " . $config['table_prefix'] . "listingsdbelements WHERE (listingsdb_id = $listingID AND listingsdbelements_field_name = 'longitude')";
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
		}
	$longitude = $misc->make_db_unsafe ($recordSet->fields['listingsdbelements_field_value']);

	$lat_dist = $search_dist / 69.0;
	$long_dist = $search_dist / abs(cos($latitude) * 69.17);

	// select all active listings whose latitude is within the search distance of the current listing's latitude
	$listingsdb = $config['table_prefix'] . "listingsdb";
	$listingsdbelements = $config['table_prefix'] . "listingsdbelements";

	$sql = "SELECT " . $listingsdbelements . ".* FROM $listingsdbelements, $listingsdb WHERE " . $listingsdb . ".listingsdb_id = " . $listingsdbelements . ".listingsdb_id AND " . $listingsdb . ".listingsdb_active = 'yes' AND (" . $listingsdbelements . ".listingsdbelements_field_name = 'latitude' AND ABS(" . $listingsdbelements . ".listingsdbelements_field_value - $latitude) < $lat_dist)";
	// don't select expired listings if we're filtering expired listings.
	if ($config['use_expiration'] == 1) {
		$sql .= " AND (" . $listingsdb . ".listingsdb_expiration > " . $conn->DBDate(time()) . ")";
	}
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
		}

	// If there are any properties within dist of listing latitude
	if ($recordSet <> false) {
		$count=0;

		// Loop through the entire set of properties found
		while (!$recordSet->EOF()){
			$pid=$misc->make_db_unsafe ($recordSet->fields['listingsdb_id']);

			// If the current property is the current listing, handle it separately
			// in order to center map on it.
			if ($pid==$listingID)
			{
				// Get the listing's thumbnail image.
				$irec=$conn->Execute("SELECT listingsimages_thumb_file_name FROM " . $config['table_prefix'] . "listingsimages WHERE listingsdb_id = $pid AND listingsimages_rank = 1");
				$fn=$misc->make_db_unsafe ($irec->fields['listingsimages_thumb_file_name']);
				$ilink=$config['baseurl']."/images/listing_photos/".$fn;

				// Gather the listing elements fields that will be used to generate
				// the html for the pop-up bubble
				$pinfo=$conn->Execute("SELECT listingsdbelements_field_name, listingsdbelements_field_value FROM " . $config['table_prefix'] . "listingsdbelements WHERE listingsdbelements_field_name IN ('address','city','state','zip','price') AND listingsdb_id = $pid");

				// Take the field information from the result set.
				// This is kind of kludgy - need to try to find either a better way
				//  of doing this, or use individual db calls to get fields.
				// Need to determine whether db calls are faster than php.
				while (!$pinfo->EOF()){
					switch ($pinfo->fields['listingsdbelements_field_name']) {
						case 'address':
							$address=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
						break;
						case 'city':
							$city=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
						break;
						case 'state':
							$state=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
						break;
						case 'zip':
							$zip=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
						break;
						case 'price':
							$price=$misc->money_formats ($misc->international_num_format($misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']), $config['number_decimals_price_fields']));
						break;
					} // switch

					$pinfo->MoveNext();
				} // while

				// Grab the listing title for the pop-up bubble
				$pinfo2=$conn->Execute("SELECT listingsdb_title FROM " . $config['table_prefix'] . "listingsdb WHERE listingsdb_id = $pid");
				$title=$misc->make_db_unsafe ($pinfo2->fields['listingsdb_title']);

				// Generate the html for the Google Map pop-up information bubble for this property.
				// *** Change this to code that pulls the html from a template file. ***

				$link = '<a href="'.$config['baseurl'].'/index.php?action=listingview&listingID='.$pid.'">';
				$gmhtml="'".'<table><tr><td align="center"><b>'. $link . $title . ' </a></b></td></tr><tr><td>';
				$gmhtml.= $link . '<img src="'.$ilink.'" altd="no image"></img></a>';
				$gmhtml.= '</td><td><b>Listing Price: '.$price.'<br><br>Property Address:</b><br>'.$address.'<br>'.$city. ', ' .$state.' '.$zip .'</td></tr></table>'."'";

				// Save the coordinates and html for the center point on the map
				$centerpoint['latitude']=$latitude;
				$centerpoint['longitude']=$longitude;
				$centerpoint['html']=$gmhtml;
			} // end if current listing

			// This is not the current listing
			else
			{
				// Get the coordinates of this data point
				$py=$misc->make_db_unsafe ($recordSet->fields['listingsdbelements_field_value']);
				$prec=$conn->Execute("SELECT * FROM " . $config['table_prefix'] . "listingsdbelements WHERE listingsdbelements_field_name = 'longitude' AND listingsdb_id = $pid");
				$px=$misc->make_db_unsafe ($prec->fields['listingsdbelements_field_value']);
				// Add this property if its longitude is less than the search distance from
				//  the current listing's.
				if (abs($px - $longitude) < $long_dist)
				{
					// Get the listing's thumbnail image.
					$irec=$conn->Execute("SELECT listingsimages_thumb_file_name FROM " . $config['table_prefix'] . "listingsimages WHERE listingsdb_id = $pid AND listingsimages_rank = 1");
					$fn=$misc->make_db_unsafe ($irec->fields['listingsimages_thumb_file_name']);
					$ilink=$config['baseurl']."/images/listing_photos/".$fn;

					// Gather the listing elements fields that will be used to generate
					// the html for the pop-up bubble
					$pinfo=$conn->Execute("SELECT listingsdbelements_field_name, listingsdbelements_field_value FROM " . $config['table_prefix'] . "listingsdbelements WHERE listingsdbelements_field_name IN ('address','city','state','zip','price') AND listingsdb_id = $pid");

					// Take the field information from the result set.
					// This is kind of kludgy - need to try to find either a better way
					//  of doing this, or use individual db calls to get fields.
					// Need to determine whether db calls are faster than php.
					while (!$pinfo->EOF()){
						switch ($pinfo->fields['listingsdbelements_field_name']) {
							case 'address':
								$address=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
							break;
							case 'city':
								$city=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
							break;
							case 'state':
								$state=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
							break;
							case 'zip':
								$zip=$misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']);
							break;
							case 'price':
								$price=$misc->money_formats ($misc->international_num_format($misc->make_db_unsafe ($pinfo->fields['listingsdbelements_field_value']), $config['number_decimals_price_fields']));
							break;
						} //switch

						$pinfo->MoveNext();
					} // while

					// Grab the listing title for the pop-up bubble
					$pinfo2=$conn->Execute("SELECT listingsdb_title FROM " . $config['table_prefix'] . "listingsdb WHERE listingsdb_id = $pid");
					$title=$misc->make_db_unsafe ($pinfo2->fields['listingsdb_title']);

					// Generate the html for the Google Map pop-up information bubble for this property.
					// *** Change this to code that pulls the html from a template file. ***
					$link = '<a href="'.$config['baseurl'].'/index.php?action=listingview&listingID='.$pid.'">';
					$gmhtml="'".'<table cellpadding="5"><tr><td align="center"><b>'. $link . $title . ' </a></b></td></tr>';
					$gmhtml.= '<tr><td><div class="thumbnail">'.$link.'<img src="'.$ilink.'" alt="no image"></img></a></div></td>';
					$gmhtml.= '<td><b>Listing Price: '.$price.'<br><br>Property Address:</b><br>'.$address.'<br>'.$city. ', ' .$state.' '.$zip .'</td></tr></table>'."'";

					// Save the coordinates and html for this data point in an array
					$otherpoint[$count]['latitude']=$py;
					$otherpoint[$count]['longitude']=$px;
					$otherpoint[$count++]['html']=$gmhtml;
				} // if
			} // else
		$recordSet->MoveNext();
		} // while
	} // end If there are any properties within dist of listing latitude

	// Generate the javascript for the map page.
	// This all goes in the header block
	$gscript.= '<style type="text/css">'."\n";
    $gscript.= '	v\:* {'."\n";
    $gscript.= '		behavior:url(#default#VML);'."\n";
    $gscript.= '	}'."\n";
    $gscript.= '</style>'."\n";

	// Set the script source and api key
	//  Note that we use v=2 even if the api_version is set to 1.  The
	//	Google API documentation states that backward compatibility should
	//	be maintained in v2, but using v=1 may break at any time.  Setting
	//	api_version to 1 will use the old GMap class and associated methods.
	$gscript.= '<script src="http://maps.google.com/maps?file=api&v=2&key=' . $api_key . '" type="text/javascript"></script>'."\n";
	$gscript.= '<script type="text/javascript">'."\n";

	// Set the basic map properties
	$gscript.= '//<![CDATA['."\n"."\n";

    $gscript.= 'function onLoad() {'."\n";
    $gscript.= '	// The Basics'."\n";
    $gscript.= '	//'."\n";
    $gscript.= '	// Taken more or less from the google API examples and modified to fit'."\n";
    $gscript.= '	var icon = new GIcon();'."\n";
    $gscript.= '	icon.image = "'. $config["baseurl"] . '/' . $icon_image_other .'";'."\n";
    $gscript.= '	icon.shadow = "'. $config["baseurl"] . '/' . $icon_shadow .'";'."\n";
    $gscript.= '	icon.iconSize = new GSize('.$icon_iconSize_x.', '.$icon_iconSize_y.');'."\n";
    $gscript.= '	icon.shadowSize = new GSize('.$icon_shadowSize_x.', '.$icon_shadowSize_y.');'."\n";
    $gscript.= '	icon.iconAnchor = new GPoint('.$icon_iconAnchor_x.', '.$icon_iconAnchor_y.');'."\n";
    $gscript.= '	icon.infoWindowAnchor = new GPoint('.$icon_infoWindowAnchor_x.', '.$icon_infoWindowAnchor_y.');'."\n";
    $gscript.= '	var cicon = new GIcon();'."\n";
    $gscript.= '	cicon.image = "'. $config["baseurl"] . '/' . $icon_image .'";'."\n";
    $gscript.= '	cicon.shadow = "'. $config["baseurl"] . '/' . $icon_shadow .'";'."\n";
    $gscript.= '	cicon.iconSize = new GSize('.$icon_iconSize_x.', '.$icon_iconSize_y.');'."\n";
    $gscript.= '	cicon.shadowSize = new GSize('.$icon_shadowSize_x.', '.$icon_shadowSize_y.');'."\n";
    $gscript.= '	cicon.iconAnchor = new GPoint('.$icon_iconAnchor_x.', '.$icon_iconAnchor_y.');'."\n";
    $gscript.= '	cicon.infoWindowAnchor = new GPoint('.$icon_infoWindowAnchor_x.', '.$icon_infoWindowAnchor_y.');'."\n";
	if ($api_version == 1) {
	    $gscript.= '	var map = new GMap(document.getElementById("map"));'."\n";
		$gscript.= '	map.setMapType(G_'.$map_type_[$map_type].');'."\n";
    	$gscript.= '	map.centerAndZoom(new GPoint('.$centerpoint['longitude'].','.$centerpoint['latitude'].'),'.$initial_zoom_level.');'."\n";
	}
	else {
	    $gscript.= '	var map = new GMap2(document.getElementById("map"));'."\n";
    	$gscript.= '	map.setCenter(new GLatLng('.$centerpoint['latitude'].','.$centerpoint['longitude'].'),'.$initial_zoom_level.', G_'.$map_type_[$map_type].');'."\n";
	}
	if ($map_control_[$map_control_type] !='none') {
		if ($api_version == 1) {
		    $gscript.= '	map.addControl(new G'. $map_control_[$map_control_type] .'());'."\n";
		}
		else {
		    $gscript.= '	map.addControl(new G'. $map_control_[$map_control_type] .'(), new GControlPosition(G_ANCHOR_'.$map_anchor[$map_control_anchor].', new GSize('.$map_control_padding_x.', '.$map_control_padding_y.')));'."\n";
		}
	}
	if ($type_control_[$type_control] !='none') {
		if ($api_version == 1) {
		    $gscript.= '	map.addControl(new G'. $type_control_[$type_control] .'());'."\n";
		}
		else {
		    $gscript.= '	map.addControl(new G'. $type_control_[$type_control] .'(), new GControlPosition(G_ANCHOR_'.$map_anchor[$type_control_anchor].', new GSize('.$type_padding_x.', '.$type_padding_y.')));'."\n";
		}
	}
	if ($scale_control_[$scale_control] !='none') {
		if ($api_version == 1) {
		    $gscript.= '	map.addControl(new G'. $scale_control_[$scale_control] .'());'."\n";
		}
		else {
		    $gscript.= '	map.addControl(new G'. $scale_control_[$scale_control] .'(), new GControlPosition(G_ANCHOR_'.$map_anchor[$scale_control_anchor].', new GSize('.$scale_padding_x.', '.$scale_padding_y.')));'."\n";
		}
	}
	if ($overview_control_[$overview_control] !='none') {
		if ($api_version == 1) {
		}
		else {
		    $gscript.= '	map.addControl(new G'. $overview_control_[$overview_control] .'(), new GControlPosition(G_ANCHOR_'.$map_anchor[$overview_control_anchor].', new GSize('.$overview_padding_x.', '.$overview_padding_y.')));'."\n";
		}
	}

	$gscript.="\n";
    $gscript.= '	// Add the current listing to the map and center the map on that location.'."\n";
	if ($api_version == 1) {
	    $gscript.= '	var cpoint = new GPoint('.$centerpoint['longitude'].','.$centerpoint['latitude'].');'."\n";
	}
	else {
	    $gscript.= '	var cpoint = new GLatLng('.$centerpoint['latitude'].','.$centerpoint['longitude'].');'."\n";
	}
    $gscript.= '	var cmarker = new GMarker(cpoint, cicon);'."\n";
    $gscript.= '	GEvent.addListener(cmarker,'."'click'".', function() {'."\n";
    $gscript.= '		cmarker.openInfoWindowHtml('.$centerpoint['html'].');'."\n";
    $gscript.= '		});'."\n";
    $gscript.= '	map.addOverlay(cmarker);'."\n"."\n";
    $gscript.= ' 	// Add other properties to the map'."\n";
	// Loop through the array and add all the other properties found within
	//  our set distance.
    for ($i=0; $i<$count; $i++)
    {
		$gscript.="\n";
		if ($api_version == 1) {
	    $gscript.='	var point'.$i.' = new GPoint('.$otherpoint[$i]['longitude'].','.$otherpoint[$i]['latitude'].');'."\n";
		}
		else {
        $gscript.='	var point'.$i.' = new GLatLng('.$otherpoint[$i]['latitude'].','.$otherpoint[$i]['longitude'].');'."\n";
		}
        $gscript.='	var marker'.$i.' = new GMarker(point'.$i.', icon);'."\n";
        $gscript.='	GEvent.addListener(marker'.$i.','."'click'".', function() {'."\n";
        $gscript.='	     	marker'.$i.'.openInfoWindowHtml('.$otherpoint[$i]['html'].');'."\n";
        $gscript.='	        });'."\n";
        $gscript.='	map.addOverlay(marker'.$i.');'."\n";
     }

	  // End the map javascript
      $gscript .= '	}'."\n".'//]]>'."\n".'</script>'."\n";

	if ($popup == 1) {
		$display = "<html>\n<head>\n";
		$display .= $gscript;
		$display .= "</head>";
		if ($api_version == 1) {
			$display .='<body onload="onLoad()">';
		}
		else {
			$display .='<body onload="onLoad()" onunload="GUnload()">';
		}
		$display .='<div id="map" style="width: '.$map_width.'; height: '.$map_height.'"></div></body>';
		$display .="</body>";
	}
	else {
		// This is the code that allows the map to be shown in the main browser window, instead
		//  of in a pop-up.
		$jscript=$gscript;
		$display = '';
	   if ($api_version == 1) {
			$display .='<body onload="onLoad()">';
		}
		else {
			$display .='<body onload="onLoad()" onunload="GUnload()">';
		}
		$display .='<div id="map" style="width: '.$map_width.'; height: '.$map_height.'"></div></body>';
	}
	return $display;
}  // end init_map()


/**
 * generate_admin_config_page()
 * This generates the html form for configuring the googlemap addon via the admin page.
 * @return The html form for configuring the googlemap addon
 */

function generate_admin_config_page() {
	global $conn, $lang, $config;
	$security = login::loginCheck('Admin', true);
	$display = '';
	if ($security === true) {
		$api_version[1] = 1;
		$api_version[2] = 2;

		$map_type[1] = 'NORMAL_MAP';
		$map_type[2] = 'SATELLITE_MAP';
		$map_type[3] = 'HYBRID_MAP';

		$map_control[1] = 'none';
		$map_control[2] = 'LargeMapControl';
		$map_control[3] = 'SmallMapControl';
		$map_control[4] = 'SmallZoomControl';

		$map_anchor[1] = 'TOP_LEFT';
		$map_anchor[2] = 'TOP_RIGHT';
		$map_anchor[3] = 'BOTTOM_LEFT';
		$map_anchor[4] = 'BOTTOM_RIGHT';

		$type_control[1] = 'none';
		$type_control[2] = 'MapTypeControl';

		$scale_control[1] = 'none';
		$scale_control[2] = 'ScaleControl';

		$overview_control[1] = 'none';
		$overview_control[2] = 'OverviewMapControl';

		// Open Connection to the Control Panel Table
		require_once($config['basepath'].'/include/misc.inc.php');
		$misc = new misc();
		// Include the Form Generation Class
		include_once($config['basepath'].'/include/class/form_generation.inc.php');
		$formGen = new formGeneration();
		// Default Options
		$yes_no[0] = 'No';
		$yes_no[1] = 'Yes';

		$asc_desc['ASC'] = 'ASC';
		$asc_desc['DESC'] = 'DESC';

		// Save any Post Data
		if (isset($_POST['api_version'])) {
			// Update addon table
			$sql = 'UPDATE ' . $config['table_prefix_no_lang'] . 'addon_googlemap SET ';
			$sql_part = '';
			foreach($_POST as $field => $value) {
				if (is_array($value)) {
					$value2 = '';
					foreach ($value as $f) {
						if ($value2 == '') {
							$value2 = "$f";
						}
						else {
							$value2 .= ",$f";
						}
					}
					$value2 = $misc->make_db_safe($value2);
					if ($sql_part == '') {
						$sql_part = "$field = $value2";
					}
					else {
						$sql_part .= " , $field = $value2";
					}
				}
				else {
					$value = $misc->make_db_safe($value);
					if ($sql_part == '') {
						$sql_part = "$field = $value";
					}
					else {
						$sql_part .= " , $field = $value";
					}
				}
			}
			$sql .= $sql_part;
			$recordSet = $conn->Execute($sql);
			if (!$recordSet) {
				$misc->log_error($sql);
			}
			$display .= '<br><b>' . $lang['configuration_saved'] . '</b><br>';
		}

		$sql = 'SELECT * from ' . $config["table_prefix_no_lang"] . 'addon_googlemap';
		$recordSet = $conn->Execute($sql);
		if (!$recordSet) {
			$misc->log_error($sql);
		}

		$display .= '<h2>Google Maps Addon Configuration. </h2><br /><br />';
		$display .= $formGen->startform('index.php?&amp;action=addon_googlemap_configure');
		// Start Map Options Section
		$display .= '<fieldset>';
		$display .= '<legend><b>Map Options</b></legend>';
		$display .= '<table cellspacing="0" cellpadding="3" width="99%" border="0">';

		$display .= '<tr class=tdshade2>';
		$display .= '<td width="130"><strong>API Version</strong></td>';
		$display .= '<td>' . $formGen->createformitem('select', 'api_version', $misc->make_db_unsafe($recordSet->fields['api_version']), false, 35, '', '', '', '', $api_version, $misc->make_db_unsafe($recordSet->fields['api_version'])) . '</td>';
		$display .= '<td>Version of the Google Maps API to use.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>API Key</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'api_key', $misc->make_db_unsafe($recordSet->fields['api_key']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['api_key'])) . '</td>';
		$display .= '<td>Google API Key for your site (required).</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Open map in pop-up window</strong></td>';
		$display .= '<td>' . $formGen->createformitem('select', 'popup', $misc->make_db_unsafe($recordSet->fields['popup']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['popup'])) . '</td>';
		$display .= '<td>Yes to open map in a separate window, No to load map in the {content} tag.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Search Distance</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'search_dist', $misc->make_db_unsafe($recordSet->fields['search_dist']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['search_dist'])) . '</td>';
		$display .= '<td>Search distance (in miles) for properties.  This is only an approximation, based on the latitude and longitude values in the listings.  Note that this won\'t work for listings without latitude or longitude set.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Initial Zoom Level</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'initial_zoom_level', $misc->make_db_unsafe($recordSet->fields['initial_zoom_level']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['initial_zoom_level'])) . '</td>';
		$display .= '<td>Enter the initial zoom level for the map.  Note that with API version 1, lower numbers are higher zoom levels, while with version 2 higher numbers are higher zoom levels.  A good starting number would be 2 for API version 1 and 15 for API version 2.</td>';
		$display .= '</tr>';

		$display .= '<td><strong>Select the initial map type to display</strong></td>';
		$display .= '<td>' . $formGen->createformitem('select', 'map_type', $misc->make_db_unsafe($recordSet->fields['map_type']), false, 35, '', '', '', '', $map_type, $misc->make_db_unsafe($recordSet->fields['map_type'])) . '</td>';
		$display .= '<td>NORMAL_MAP is the regular google map.  SATELLITE_MAP is satellite imagery (not available at all zoom levels).  HYBRID_MAP is the satellite imagery with a partial map overlay.  Note that these can be selected by the user via the map type control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Map Height</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'map_height', $misc->make_db_unsafe($recordSet->fields['map_height']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['map_height'])) . '</td>';
		$display .= '<td>Enter the default map height.  You may use standard html/css designations: e.g., (500px, 100%, etc...)</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Map Width</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'map_width', $misc->make_db_unsafe($recordSet->fields['map_width']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['map_width'])) . '</td>';
		$display .= '<td>Enter the default map width.  You may use standard html/css designations: e.g., (500px, 100%, etc...)</td>';
		$display .= '</tr>';

		$display .= '</table>';
		$display .= '</fieldset><br />';

		// Start Icon Options Section
		$display .= '<fieldset>';
		$display .= '<legend><b>Listing Information Bubble Options</b></legend>';
		$display .= '<table cellspacing="0" cellpadding="3" width="99%" border="0">';

		// *** NOT IMPLEMENTED YET ***
//		$display .= '<tr class=tdshade2>';
//		$display .= '<td width="130"><strong>Info Bubble Template</strong></td>';
//		$display .= '<td>' . $formGen->createformitem('text', 'info_bubble_template', $misc->make_db_unsafe($recordSet->fields['info_bubble_template']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['info_bubble_template'])) . '</td>';
//		$display .= '<td>Template to use for the pop-up information bubble for each listing on the map.</td>';
//		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Icon Image</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'icon_image', $misc->make_db_unsafe($recordSet->fields['icon_image']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['icon_image'])) . '</td>';
		$display .= '<td>Image to use for the listing property icon.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Secondary Icon Image</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'icon_image_other', $misc->make_db_unsafe($recordSet->fields['icon_image_other']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['icon_image_other'])) . '</td>';
		$display .= '<td>Image to use for all the other property icons.  It is assumed that these two icons are the same size.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Icon Width</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'icon_iconSize_x', $misc->make_db_unsafe($recordSet->fields['icon_iconSize_x']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['icon_iconSize_x'])) . '</td>';
		$display .= '<td>Width of the icon file (in pixels).</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Icon Height</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'icon_iconSize_y', $misc->make_db_unsafe($recordSet->fields['icon_iconSize_y']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['icon_iconSize_y'])) . '</td>';
		$display .= '<td>Width of the icon file (in pixels).</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Icon Shadow Image</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'icon_shadow', $misc->make_db_unsafe($recordSet->fields['icon_shadow']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['icon_shadow'])) . '</td>';
		$display .= '<td>Image to use for the property icon shadows.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Shadow Width</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'icon_shadowSize_x', $misc->make_db_unsafe($recordSet->fields['icon_shadowSize_x']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['icon_shadowSize_x'])) . '</td>';
		$display .= '<td>Width of the icon shadow file (in pixels).</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Shadow Height</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'icon_shadowSize_y', $misc->make_db_unsafe($recordSet->fields['icon_shadowSize_y']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['icon_shadowSize_y'])) . '</td>';
		$display .= '<td>Width of the icon shadow file (in pixels).</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Icon Anchor X</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'icon_iconAnchor_x', $misc->make_db_unsafe($recordSet->fields['icon_iconAnchor_x']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['icon_iconAnchor_x'])) . '</td>';
		$display .= '<td>The x coordinate relative to the top left corner of the icon image at which this icon is anchored to the map.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Icon Anchor Y</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'icon_iconAnchor_y', $misc->make_db_unsafe($recordSet->fields['icon_iconAnchor_y']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['icon_iconAnchor_y'])) . '</td>';
		$display .= '<td>The y coordinate relative to the top left corner of the icon image at which this icon is anchored to the map.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Info Window Anchor X</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'icon_infoWindowAnchor_x', $misc->make_db_unsafe($recordSet->fields['icon_infoWindowAnchor_x']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['icon_infoWindowAnchor_x'])) . '</td>';
		$display .= '<td>The x coordinate relative to the top left corner of the icon image at which this icon is anchored to the map.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Info Window Anchor Y</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'icon_infoWindowAnchor_y', $misc->make_db_unsafe($recordSet->fields['icon_infoWindowAnchor_y']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['icon_infoWindowAnchor_y'])) . '</td>';
		$display .= '<td>The y coordinate relative to the top left corner of the icon image at which this icon is anchored to the map.</td>';
		$display .= '</tr>';

		$display .= '</table>';
		$display .= '</fieldset><br />';

		// Start Control Options Section
		$display .= '<fieldset>';
		$display .= '<legend><b>Map Control Options</b></legend>';
		$display .= '<table cellspacing="0" cellpadding="3" width="99%" border="0">';

		$display .= '<tr class=tdshade2>';
		$display .= '<td width="130"><strong>Map Control</strong></td>';
		$display .= '<td>' . $formGen->createformitem('select', 'map_control_type', $misc->make_db_unsafe($recordSet->fields['map_control_type']), false, 35, '', '', '', '', $map_control, $misc->make_db_unsafe($recordSet->fields['map_control_type'])) . '</td>';
		$display .= '<td>Map control to use.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Map Control Anchor</strong></td>';
		$display .= '<td>' . $formGen->createformitem('select', 'map_control_anchor', $misc->make_db_unsafe($recordSet->fields['map_control_anchor']), false, 35, '', '', '', '', $map_anchor, $misc->make_db_unsafe($recordSet->fields['map_control_anchor'])) . '</td>';
		$display .= '<td>Location on the map to display this control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Map Control Padding X</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'map_control_padding_x', $misc->make_db_unsafe($recordSet->fields['map_control_padding_x']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['map_control_padding_x'])) . '</td>';
		$display .= '<td>Horizontal padding around this control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Map Control Padding Y</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'map_control_padding_y', $misc->make_db_unsafe($recordSet->fields['map_control_padding_y']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['map_control_padding_y'])) . '</td>';
		$display .= '<td>Vertical padding around this control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td width="130"><strong>Map Type Control</strong></td>';
		$display .= '<td>' . $formGen->createformitem('select', 'type_control', $misc->make_db_unsafe($recordSet->fields['type_control']), false, 35, '', '', '', '', $type_control, $misc->make_db_unsafe($recordSet->fields['type_control'])) . '</td>';
		$display .= '<td>Map type control to use.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Map Type Control Anchor</strong></td>';
		$display .= '<td>' . $formGen->createformitem('select', 'type_control_anchor', $misc->make_db_unsafe($recordSet->fields['type_control_anchor']), false, 35, '', '', '', '', $map_anchor, $misc->make_db_unsafe($recordSet->fields['type_control_anchor'])) . '</td>';
		$display .= '<td>Location on the map to display this control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Map Type Control Padding X</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'type_padding_x', $misc->make_db_unsafe($recordSet->fields['type_padding_x']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['type_padding_x'])) . '</td>';
		$display .= '<td>Horizontal padding around this control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Map Type Control Padding Y</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'type_padding_y', $misc->make_db_unsafe($recordSet->fields['type_padding_y']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['type_padding_y'])) . '</td>';
		$display .= '<td>Vertical padding around this control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td width="130"><strong>Scale Control</strong></td>';
		$display .= '<td>' . $formGen->createformitem('select', 'scale_control', $misc->make_db_unsafe($recordSet->fields['scale_control']), false, 35, '', '', '', '', $scale_control, $misc->make_db_unsafe($recordSet->fields['scale_control'])) . '</td>';
		$display .= '<td>Map scale control to use.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Scale Control Anchor</strong></td>';
		$display .= '<td>' . $formGen->createformitem('select', 'scale_control_anchor', $misc->make_db_unsafe($recordSet->fields['scale_control_anchor']), false, 35, '', '', '', '', $map_anchor, $misc->make_db_unsafe($recordSet->fields['scale_control_anchor'])) . '</td>';
		$display .= '<td>Location on the map to display this control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Scale Control Padding X</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'scale_padding_x', $misc->make_db_unsafe($recordSet->fields['scale_padding_x']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['scale_padding_x'])) . '</td>';
		$display .= '<td>Horizontal padding around this control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Scale Control Padding Y</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'scale_padding_y', $misc->make_db_unsafe($recordSet->fields['scale_padding_y']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['scale_padding_y'])) . '</td>';
		$display .= '<td>Vertical padding around this control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td width="130"><strong>Overview Control</strong></td>';
		$display .= '<td>' . $formGen->createformitem('select', 'overview_control', $misc->make_db_unsafe($recordSet->fields['overview_control']), false, 35, '', '', '', '', $overview_control, $misc->make_db_unsafe($recordSet->fields['overview_control'])) . '</td>';
		$display .= '<td>Map overview control.  This is not available with API Version 1.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Overview Control Anchor</strong></td>';
		$display .= '<td>' . $formGen->createformitem('select', 'overview_control_anchor', $misc->make_db_unsafe($recordSet->fields['overview_control_anchor']), false, 35, '', '', '', '', $map_anchor, $misc->make_db_unsafe($recordSet->fields['overview_control_anchor'])) . '</td>';
		$display .= '<td>Location on the map to display this control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade2>';
		$display .= '<td><strong>Overview Control Padding X</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'overview_padding_x', $misc->make_db_unsafe($recordSet->fields['overview_padding_x']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['overview_padding_x'])) . '</td>';
		$display .= '<td>Horizontal padding around this control.</td>';
		$display .= '</tr>';

		$display .= '<tr class=tdshade1>';
		$display .= '<td><strong>Overview Control Padding Y</strong></td>';
		$display .= '<td>' . $formGen->createformitem('text', 'overview_padding_y', $misc->make_db_unsafe($recordSet->fields['overview_padding_y']), false, 35, '', '', '', '', $yes_no, $misc->make_db_unsafe($recordSet->fields['overview_padding_y'])) . '</td>';
		$display .= '<td>Vertical padding around this control.</td>';
		$display .= '</tr>';

		$display .= '</table>';
		$display .= '</fieldset><br />';
		$display .= '<table width="99%" align="right"><tr><td align="right">' . $formGen->createformitem('submit', '', 'Save Changes') . '</td></tr></table>';
		$display .= $formGen->endform();
	} // end if security
	else {
		$display .= '<div class="error_text">' . $lang['access_denied'] . '</div>';
	}
	return $display;
}

/**
 * insert_listing_field()
 * This was taken almost verbatim from include/template_editor.inc.php.
 * The only reason the code is duplicated here is because the code in
 * template_editor.inc.php is designed around the form, and requires
 * $_POST[] to be properly set in order to work.  The only time this
 * addon uses this method is during the initial install, and then only
 * if the database does not already have fields named "latitude" and
 * "longitude".
 */
function insert_listing_field($field_type, $field_name, $field_caption, $default_text, $field_elements, $rank, $search_rank, $search_result_rank, $required, $location, $display_on_browse, $search_step, $display_priv, $searchable, $search_label, $search_type, $property_class)
{
	// include global variables
	global $conn, $lang, $config;
	// Include the misc Class
	require_once($config['basepath'] . '/include/misc.inc.php');
	$misc = new misc();

	$field_type = $misc->make_db_safe($field_type);
	$field_name = $misc->make_db_safe($field_name);
	$field_caption = $misc->make_db_safe($field_caption);
	$default_text = $misc->make_db_safe($default_text);
	$field_elements = $misc->make_db_safe($field_elements);
	$rank = $misc->make_db_safe($rank);
	$search_rank = $misc->make_db_safe($search_rank);
	$search_result_rank = $misc->make_db_safe($search_result_rank);
	$required = $misc->make_db_safe($required);
	$location = $misc->make_db_safe($location);
	$display_on_browse = $misc->make_db_safe($display_on_browse);
	$search_step = $misc->make_db_safe($search_step);
	$display_priv = $misc->make_db_safe($display_priv);
	$searchable = $misc->make_db_safe($searchable);
	$search_label = $misc->make_db_safe($search_label);
	$search_type = $misc->make_db_safe($search_type);

	$id_rand = rand(0, 999999);
	$sql = "INSERT INTO " . $config['table_prefix'] . "listingsformelements (listingsformelements_field_type, listingsformelements_field_name, listingsformelements_field_caption, listingsformelements_default_text, listingsformelements_field_elements, listingsformelements_rank, listingsformelements_search_rank, listingsformelements_search_result_rank, listingsformelements_required, listingsformelements_location, listingsformelements_display_on_browse, listingsformelements_search_step, listingsformelements_searchable, listingsformelements_search_label, listingsformelements_search_type,listingsformelements_display_priv) VALUES ($field_type,$id_rand,$field_caption,$default_text,$field_elements,$rank,$search_rank,$search_result_rank,$required,$location,$display_on_browse,$search_step,$searchable,$search_label,$search_type,$display_priv)";
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
	}
	// Now we need to get the field ID
	$sql = 'SELECT listingsformelements_id FROM ' . $config['table_prefix'] . 'listingsformelements WHERE listingsformelements_field_name = ' . $id_rand;
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
	}
	$listingsformelements_id = $recordSet->fields['listingsformelements_id'];
	// Set Real Name
	$sql = 'UPDATE ' . $config['table_prefix'] . 'listingsformelements SET listingsformelements_field_name = ' . $field_name . ' WHERE listingsformelements_field_name = ' . $id_rand;
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
	}
	// We should now add a blank field for each listing that already exist.
	$sql = 'SELECT listingsdb_id, userdb_id FROM ' . $config['table_prefix'] . 'listingsdb';
	$recordSet = $conn->Execute($sql);
	if ($recordSet === false) {
		$misc->log_error($sql);
	}
	$id = array();
	$user = array();
	while (!$recordSet->EOF) {
		$id[] = $recordSet->fields['listingsdb_id'];
		$user[] = $recordSet->fields['userdb_id'];
		$recordSet->MoveNext();
	} // while
	$count = count($id);
	$x = 0;
	while ($x < $count) {
		$sql = "INSERT INTO " . $config['table_prefix'] . "listingsdbelements (listingsdbelements_field_name, listingsdb_id,userdb_id,listingsdbelements_field_value) VALUES ($field_name,'$id[$x]','$user[$x]','')";
		$recordSet = $conn->Execute($sql);
		if ($recordSet === false) {
			$misc->log_error($sql);
		}
		$x++;
	}
	// Add Listing Field to property class
	foreach($property_class as $class_id) {
		$sql = 'INSERT INTO ' . $config['table_prefix_no_lang'] . 'classformelements (class_id,listingsformelements_id) VALUES (' . $class_id . ',' . $listingsformelements_id . ')';
		$recordSet = $conn->Execute($sql);
		if ($recordSet === false) {
			$misc->log_error($sql);
		}
	}
}
?>
